package com.sinosoft.weixin.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;

/**
 * Created by huzhengying on 2017/11/18.
 */
public class HttpClientUtils {
    private static org.apache.logging.log4j.Logger logger = LogManager.getLogger(HttpClientUtils.class);
    public static final String fail_Result = "FAIL";
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String sendHttpRequest(String inputdata,String url){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            if(!StringUtils.isNotBlank(url)){
                throw new RuntimeException("请求路径不能为空！");
            }
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type","text/json");
            post.setEntity(new StringEntity(inputdata,"utf-8"));

            response = httpClient.execute(post);

            if(200 == response.getStatusLine().getStatusCode()){
                String result = EntityUtils.toString(response.getEntity());
                logger.info(result);
                return result;
            }else {
                logger.error("请求失败！响应码为：" + response.getStatusLine().getStatusCode());
                return fail_Result;
            }
        }catch (Exception ex){
            logger.error("请求失败！", ex);
        }finally {
            IOUtils.closeQuietly(response);
            IOUtils.closeQuietly(httpClient);
        }
        return fail_Result;
    }
}
